package tools.chapter14;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Kevin
 * @date 2020/2/24 14:08
 * 存在活锁。这个例子可以稍微改下，成功转账后应该跳出循环。加个随机重试时间避免活锁
 */
public class Account {
    private int balance;
    private final Lock lock = new ReentrantLock();
    //转账
    void transfer(Account tar, int amt) throws InterruptedException {
        while(true) {
            if (this.lock.tryLock()) {
                try {
                    if (tar.lock.tryLock()) {
                        try {
                            this.balance -= amt;
                            tar.balance += amt;
                        } finally {
                            tar.lock.unlock();
                        }
                    }//if
                } finally {
                    this.lock.unlock();
                    break;
                }
            }//if
            Thread.sleep((long) Math.random());
        }//while
    }//transfer

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date start = format.parse("2019-12-27");
        long date = start.getTime();
        date -= 1000;
        Date end = new Date(date);
        System.out.println(end.toString());
    }
}
